package com.cyz.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyz.admin.service.Admin_MenuService;
import com.cyz.admin.service.Admin_UserService;
import com.cyz.admin.service.RoleService;
import com.cyz.common.bean.User;
import com.cyz.common.dto.UserDto;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.exception.MyException;
import com.cyz.common.mapper.UserMapper;
import com.cyz.common.security.MyUserDetails;
import com.cyz.common.utils.*;
import com.cyz.admin.vo.AdminUserVo;
import com.cyz.admin.vo.MenuVo;
import com.cyz.admin.vo.RoutersVo;
import com.cyz.admin.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
* @author 34928
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2023-02-22 10:58:38
*/
@Service
@Transactional
public class AdminUserServiceImpl extends ServiceImpl<UserMapper, User>
    implements Admin_UserService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private MyRedisUtil myRedisUtil;
    @Autowired
    private Admin_MenuService adminAdminMenuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
//    @Autowired
//    private RoleMapper roleMapper;
//    @Autowired
//    private MenuMapper menuMapper;


    @Override
    public R login(UserDto userDto) {
        //将user信息封装到authentication实现类中
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDto.getUserName(),userDto.getPassword());
        //调用authenticate进行认证
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //如果取出authentication为空，认证失败
        if(ObjectUtils.isEmpty(authentication)){
            throw new MyException(MyEnums.LOGIN_ERROR);
        }
        //认证成功取出数据
        MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
        if(!MyEnums.USER_TYPE_ADMIN.equals(myUserDetails.getUser().getType())){
            throw new MyException(MyEnums.LOGIN_ERROR);
        }
        if(myUserDetails.getUser().getStatus().equals(MyEnums.USER_BAN)){
            throw new MyException(MyEnums.LOGIN_BAN);
        }
        User user = myUserDetails.getUser();
        //获取数据id
        Integer id = user.getId();
        //根据id生成token
        String jwt = JwtUtil.createJWT(String.valueOf(id));
        //将数据存入redis
//        redisUtil.setCacheObject(MyEnums.ADMIN_REDIS_NAME +id,myUserDetails);
        myRedisUtil.myStringSet(MyEnums.ADMIN_REDIS_NAME +id,myUserDetails);
        //返回数据
        return R.success(jwt);
    }

    @Override
    public R getInfo() {
        //获取当前登录用户
        MyUserDetails loginUser = SecurityUtils.getLoginUser();
        //根据id查询权限信息
        List<String> menus = adminAdminMenuService.queryMenusById(SecurityUtils.getUserId());
        //根据id查询角色信息
        List<String> roles = roleService.queryRolesById(SecurityUtils.getUserId());
//        List<String> roles = roleMapper.queryRolesById(SecurityUtils.getUserId());
        //获取用户信息，封装vo
        UserVo userVo = BeanCopyUtil.copyBean(loginUser.getUser(), UserVo.class);
        AdminUserVo adminUserVo = new AdminUserVo(menus,roles,userVo);
        //返回数据
        return R.success(adminUserVo);
    }

    @Override
    public R getRouters() {
        //获取用户id
        Integer userId = SecurityUtils.getUserId();
        //根据id查询菜单
        List<MenuVo> menuVos = adminAdminMenuService.getRouterMenuTreeByUserId(userId);
        //返回数据
        return R.success(new RoutersVo(menuVos));
    }

    @Override
    public R logout() {
        //获取当前登录用户id
        Integer userId = SecurityUtils.getUserId();
        //根据ID删除redis中对应的值
//        redisUtil.deleteObject(MyEnums.ADMIN_REDIS_NAME+userId);
        myRedisUtil.myDeleteKey(MyEnums.ADMIN_REDIS_NAME+userId);
        //返回退出成功信息
        return R.success(MyEnums.SUCCESS_LOGOUT.getMsg());
    }

    @Override
    public R updateMsg(UserDto userDto) {
        //转化dto
        User user = BeanCopyUtil.copyBean(userDto, User.class);

        //加密密码
        if(!user.getPassword().isEmpty()){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        //保存数据
        boolean flag = userMapper.updateUser(user);
        //错误判断
        if(flag){
            //根据ID查询更新后的用户信息
            user = getById(userDto.getId());
            //返回数据
            return R.success(user);
        }
        return R.error(MyEnums.UPDATE_FAIL);
    }
}




